<script setup lang="ts" name="Login">
import API from "@/api";
import router from "@/router";
import userinfo from "@/store/userinfo";
const { t } = useI18n();
const piniaUserinfo: any = userinfo();
const countdown = ref(0);
const route = useRoute();
const global: any = getCurrentInstance()?.appContext.config.globalProperties;
const data: any = reactive({
  signList: [
    {
      label: computed(() => t("login.title1")),
      value: "phone",
    },
    {
      label: computed(() => t("login.title2")),
      value: "email",
    },
  ],
  signType: "signIn", // 登录, 注册,忘记密码
  loginType: "phone", // phone, email
  signInRef: null,
  callBackRef: null,
  signInForm: {
    phone: "",
    msgId: "",
    mail: "",
    type: "",
    verificationCode: "",
    passwd: "",
    newPasswd: "",
    promotionCode: "",
  },
  isLoading: false,
  isChecked: false,
  isDisableCode: false,
  getCodeText: "",
  getCodeDisabled: false,
  timer: null,
  phoneTimeout: 0,
  emailTimeout: 0,
  showPassword:false,
  showNewPassword:false
});

const {
  signList,
  signType,
  signInForm,
  signInRef,
  isLoading,
  isDisableCode,
  loginType,
  getCodeText,
  getCodeDisabled,
  timer,
  phoneTimeout,
  emailTimeout,
  showPassword,
  showNewPassword
} = toRefs(data);
const mailValidator = (val: string) => {
  const regExp = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!regExp.test(val)) {
    return t("login.test18");
  }
  return true;
};
const passValidator = (val: string) => {
  if (
    !/^(?!.*\s)[A-Za-z0-9!?@#$%^&*()_+=\-.,:;<>/\\[\]{}|~]{8,16}$/.test(val)
  ) {
    return t("login.test1");
  }
  return true;
};
const codeText = computed(() => {
  let textName;
  if (!getCodeDisabled.value) {
    textName = t("login.test17");
  } else {
    textName = getCodeText.value;
  }
  return textName;
});
const comfirmPassValidator = (val: string) => {
  if (!val) {
    return t("login.test2");
  } else if (val !== signInForm.value.passwd) {
    return t("login.test3");
  } else {
    return true;
  }
};
//siginType 登录，注册，忘记密码
const showTextTitle = computed(() => {
  let textName: any = {
    loginTitle: null,
    titleRemark: null,
    btnName: null,
  };
  switch (signType.value) {
    case "signIn":
      return {
        ...textName,
        loginTitle: t("login.test4"),
        titleRemark: t("login.test13"),
        btnName: t("login.login"),
      };
    case "signUp":
      return {
        ...textName,
        loginTitle: t("login.test5"),
        titleRemark: t("login.test14"),
        btnName: t("login.register"),
      };
    case "callBackPwd":
      return {
        ...textName,
        loginTitle: t("login.test15"),
        titleRemark: t("login.test16"),
        btnName: t("login.callBackPwd"),
      };
    default:
      return "";
  }
});

const formShow = computed(() => {
  let formType = {
    phone: false,
    verifyCode: false,
    inviteCode: false,
    passPwd: false,
    email: false,
    newPasswd: false,
    type: 0, //1:手机号码登录，2：手机注册，3：手机忘记密码,4:邮箱登录,5:邮箱注册,6:邮箱忘记密码
  };
  if (loginType.value === "phone") {
    switch (signType.value) {
      case "signIn":
        return {
          ...formType,
          phone: true,
          passPwd: true,
          type: 1,
        };
      case "signUp":
        return {
          ...formType,
          phone: true,
          passPwd: true,
          verifyCode: true,
          inviteCode: true,
          newPasswd: true,
          type: 2,
        };
      case "callBackPwd":
        return {
          ...formType,
          phone: true,
          verifyCode: true,
          inviteCode: true,
          type: 3,
        };
    }
  } else {
    switch (signType.value) {
      case "signIn":
        return {
          ...formType,
          email: true,
          passPwd: true,
          type: 4,
        };
      case "signUp":
        return {
          ...formType,
          email: true,
          passPwd: true,
          verifyCode: true,
          inviteCode: true,
          newPasswd: true,
          type: 5,
        };
      case "callBackPwd":
        return {
          ...formType,
          email: true,
          verifyCode: true,
          inviteCode: true,
          type: 6,
        };
    }
  }
});

const handleActiveSign = (item: any) => {
  loginType.value = item.value;
  getCodeText.value = t("login.test17");
  countdown.value = 0;
  let remainTime =
  loginType.value == "email" ? emailTimeout.value : phoneTimeout.value;
  remainTime = Math.ceil((remainTime - Date.now()) / 1000);
  getCodeDisabled.value = remainTime > 0;
  if (getCodeDisabled.value) {
    getCodeText.value = remainTime;
    getCodeTimer();
  } else {
    getCodeText.value = t("login.test17");
  }
};

// 登录 注册 修改密码
const handleFormSubmit = () => {
  console.log(signInRef.value, "signInRef.value");
  if (!signInRef.value) return;
  signInRef.value?.validate().then(() => {
    let formData = signInRef.value?.getValues();
    isLoading.value = true;
    let params = {
      ...formData,
      msgId: signInForm.value.msgId,
      type: formShow.value?.type === 1 || formShow.value?.type === 2 ? 1 : 2,
    };
    console.log(formShow.value?.type, "formShow.value?.type");
    switch (formShow.value?.type) {
      case 1: //登录
      case 4: //登录
        handleLogin(params);
        break;
      case 2: //注册
      case 5: //注册
        handleRegister(params);
        break;
      case 3: //修改密码
      case 6: //修改密码
        handleVerifyCode(params);
        break;
    }
  });
};
//登录
const handleLogin = (params: any) => {
  let questData = {
    ...params,
    phone: "91" + params.phone,
  };
  API.loginAPI(questData)
    .then((res: any) => {
      if (res?.code === 200) {
        let data = {
          user: JSON.parse(res.data.user),
          token: res.data.token,
        };
        piniaUserinfo.setUserinfo(data);
        isLoading.value = false;
        router.push({ path: "/home" });
      }
    })
    .finally(() => {
      isLoading.value = false;
    });
};
// 注册
const handleRegister = (params: any) => {
  let questData = {
    ...params,
    phone: "91" + params.phone,
  };
  API.registerAPI(questData)
    .then((res: any) => {
      if (res?.code === 200) {
        isLoading.value = false;
        global.message(t("login.test6"));
        signType.value = "signIn";
        //注册成功后直接走登录流程
        // signInForm.value.account = signInForm.value.account
        // signInForm.value.passwd = signInForm.value.passwd
      }
    })
    .finally(() => {
      isLoading.value = false;
    });
};
// 修改密码
const handleVerifyCode = (params: any) => {};
const handleToSwitch = (type: string) => {
  signType.value = type;
};
const goLastPage = () => {
  router.push({ path: "/home" });
};
const handleForgetPwd = () => {
  signType.value = "callBackPwd";
};

// 开始定时器
const getCodeTimer = () => {
  clearInterval(timer.value);
  timer.value = setInterval(() => {
    let overTime =
      loginType.value == "phone" ? phoneTimeout.value : emailTimeout.value; //定时器结束时间
    let remainTime = Math.ceil((overTime - Date.now()) / 1000);
    console.log(remainTime);
    if (remainTime > 0) {
      getCodeText.value = remainTime;
    } else {
      if (loginType.value == "phone") {
        phoneTimeout.value = 0;
      } else {
        emailTimeout.value = 0;
      }
      getCodeText.value = t("login.test17");
      clearInterval(timer.value);
      getCodeDisabled.value = false;
    }
  }, 1000);
};
// 倒计时
// const getCodeTimer = (disable: any) => {
//   countdown.value = loginType.value == 'phone' ? 60 : phoneCount.value;
//   if (timer.value) {
//     return;
//   }
//   const callback = function () {
//     if (countdown.value <= 0) {
//       getCodeText.value = t('login.test17');
//       disable.value = false;
//       clearInterval(timer.value);
//     } else {
//       getCodeText.value = countdown.value--;
//     }
//   };
//   callback();
//   timer.value = setInterval(callback, 1000);
// };

// 获取code
const getCodeData = () => {
  console.log(formShow.value?.type, "formShow.value?.type");
  if (formShow.value?.type === 2) {
    if (!signInForm.value.phone) {
      global.message(t("login.test8"), { type: "danger" });
      return;
    }
  } else {
    if (!signInForm.value.phone) {
      global.message(t("login.test19"), { type: "danger" });
      return;
    }
  }
  getCodeDisabled.value = true;
  if (loginType.value == "phone") {
    phoneTimeout.value = Date.now() + 60000;
  } else {
    emailTimeout.value = Date.now() + 60000;
  }
  getCodeTimer();
  getVerifiyCode();
};
const getVerifiyCode = () => {
  if (loginType.value === "phone") {
    API.getPhoneCode({ phone: "91" + signInForm.value.phone }).then(
      (res: any) => {
        if (res?.code === 200) {
          signInForm.value.msgId = res.data;
        }
      }
    );
  } else {
    API.getMailCode({ mail: signInForm.value.mail }).then((res: any) => {
      if (res?.code === 200) {
        signInForm.value.msgId = "";
      }
    });
  }
};
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value
}
const toggleNewPasswordVisibility = () => {
  showNewPassword.value = !showNewPassword.value
}
// 监听登录注册切换
watch(
  () => route?.query?.type,
  (val) => {
    if (val) {
      switch (val) {
        case "signUp":
          signType.value = "signUp";
          break;
        default:
          signType.value = "signIn";
          break;
      }
    }
  },
  {
    immediate: true,
  }
);
watch(
  () => signType.value,
  (val) => {
    switch (val) {
      case "signUp":
        router.replace("/login?type=signUp");
        break;
      default:
        router.replace("/login?type=signIn");
        break;
    }
  }
);

// 填入邀请码
watch(
  () => route?.query?.code,
  (val) => {
    if (val) {
      signInForm.value.promotionCode = val;
      isDisableCode.value = true;
    }
  },
  {
    immediate: true,
  }
);
</script>

<template>
  <div class="loginWrap">
    <DetailHeader :isNeedBackIcon="true" bg="transparent" :isNeedRedirectPage="true" @goBackPage="goLastPage"/>
    <div class="loginTitle">India Lucky Online Lottery</div>
    <div class="content">
      <div class="top">
        <div class="left">
          <h3>{{ showTextTitle?.loginTitle }}</h3>
          <p>{{ showTextTitle?.titleRemark }}</p>
        </div>
        <div class="right">
          <img src="../../assets/images/Login/logo.png" alt="" />
        </div>
      </div>

      <div
        class="formCard"
        :class="{
          signIn: signType === 'signIn',
          signUp: signType === 'signUp',
        }"
      >
        <div>
          <div class="tabs">
            <div
              v-for="(item, index) in signList"
              :key="index"
              class="tabItem"
              :class="{
                active: item.value === loginType,
              }"
              @click="handleActiveSign(item)"
            >
              {{ item.label }}
            </div>
          </div>
          <div class="formContent">
            <van-form ref="signInRef" label-align="top">
              <div class="phoneInfo" v-if="formShow?.phone">
                <van-field
                  v-model="signInForm.phone"
                  :label="t('login.test21')"
                  required
                  maxlength="11"
                  type="tel"
                  name="phone"
                  :rules="[{ required: true, message: t('login.test8') }]"
                >
                  <template #input>
                    <div class="phone-container">
                      <div class="phoneLeft">+91</div>
                      <input v-model="signInForm.phone" />
                    </div>
                  </template>
                </van-field>
              </div>
              <van-field
                v-model="signInForm.mail"
                :label="t('login.test22')"
                v-if="formShow?.email"
                required
                name="mail"
                :rules="[{ validator: mailValidator }]"
              />
              <van-field
                v-if="formShow?.passPwd"
                v-model="signInForm.passwd"
                :label="t('login.test23')"
                required
                name="passwd"
                :right-icon="showPassword ? 'eye' : 'closed-eye'"
                @click-right-icon="togglePasswordVisibility"
                :type="showPassword ? 'text' : 'password'"
                :rules="[{ validator: passValidator }]"
              />
              <van-field
                v-if="formShow?.newPasswd"
                v-model="signInForm.newPasswd"
                :label="t('login.test24')"
                required
                name="newPasswd"
                :right-icon="showNewPassword ? 'eye' : 'closed-eye'"
                @click-right-icon="toggleNewPasswordVisibility"
                :type="showNewPassword ? 'text' : 'password'"
                :rules="[{ validator: comfirmPassValidator }]"
              />
              <div class="phoneInfo" v-if="formShow?.verifyCode">
                <van-field
                  v-model="signInForm.verificationCode"
                  :label="t('login.test25')"
                  required
                  type="digit"
                  class="registerLeft"
                  name="verificationCode"
                  :rules="[{ required: true, message: t('login.test20') }]"
                >
                  <template #input>
                    <input
                      class="verifyCodeWidth"
                      v-model="signInForm.verificationCode"
                    />
                    <van-button
                      round
                      block
                      class="getCode"
                      type="primary"
                      @click="getCodeData"
                      :disabled="getCodeDisabled"
                    >
                      {{ codeText }}
                    </van-button>
                  </template>
                </van-field>
              </div>
              <van-field
                v-if="formShow?.inviteCode"
                v-model="signInForm.promotionCode"
                :disabled="isDisableCode"
                :label="t('login.test26')"
                type="text"
                name="promotionCode"
              />
            </van-form>
          </div>
        </div>
      </div>
      <div class="btnWrap">
        <van-button
          round
          block
          type="primary"
          :loading="isLoading"
          @click="handleFormSubmit"
        >
          {{ showTextTitle?.btnName }}
        </van-button>
        <div class="bottomRemark" v-show="signType === 'signIn'">
          <div class="hasAccount" @click="handleToSwitch('signUp')">
            {{ t('login.test28') }}<span>{{ t('login.test29') }}</span>
          </div>
          <!-- <div class="hasAccount" @click="handleForgetPwd">忘记密码？</div> -->
        </div>
        <div
          class="hasAccount"
          v-show="signType === 'signUp'"
          @click="handleToSwitch('signIn')"
        >
        {{ t('login.test30') }}<span>{{ t('login.test31') }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.loginWrap {
  background: #f3f8fe;
  background-image: url("../../assets/images/Login/bg.png");
  background-repeat: no-repeat;
  background-size: 100% auto;
  background-position: top;
  height: 100%;
  position: relative;
  .loginTitle {
    margin-top: 21px;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 60px;
    line-height: 60px;
    color: #343c4b;
    font-family: Inter;
    font-size: 16px;
    font-style: normal;
    font-weight: 600;
    position: absolute;
    top: -22px;
    left: 98px;
  }
  .content {
    .top {
      display: flex;
      flex-direction: row;
      align-items: center;
      padding: 0 16rem;
      .left {
        & > h3 {
          color: #343c4b;
          font-size: 24rem;
          font-weight: 600;
        }

        & > p {
          margin-top: 7rem;
          color: #858d9c;
          font-size: 12rem;
          font-weight: 400;
          line-height: 20rem;
        }
      }
      .right {
        img {
          height: 142rem;
        }
      }
    }

    .formCard {
      border-radius: 14rem;
      overflow: hidden;
      margin: 16rem;
      background: #f4f8fe;
      background-position: top;
      background-repeat: no-repeat;
      background-size: 100% auto;
      filter: drop-shadow(0px 4px 16px rgba(87, 110, 156, 0.1));

      &.signIn {
        background-image: url("../../assets/images/Login/cardbg1.svg");
      }

      &.signUp {
        background-image: url("../../assets/images/Login/cardbg2.svg");
      }

      .tabs {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        height: 50rem;
        .tabItem {
          display: flex;
          justify-content: center;
          align-items: center;
          flex: 1;
          color: #535b6c;
          font-size: 16rem;
          font-weight: 600;
          height: 100%;
          overflow: hidden;
          &.active {
            position: relative;
            &::before {
              content: "";
              position: absolute;
              bottom: 0;
              left: 50%;
              transform: translateX(-50%);
              width: 32rem;
              height: 4rem;
              border-radius: 2rem;
              background: #ff2d55;
            }
          }
        }
      }

      .formContent {
        margin-top: 20rem;
        background: #fff;
        padding-bottom: 20rem;
        .phoneInfo {
          display: flex;
          align-items: center;
          justify-content: center;
          .phone-container {
            display: flex;
            align-items: center;
            gap: 8rem;
            width: 100%;
          }
          .phoneLeft {
            line-height: 44rem;
            height: 44px;
            border-radius: 24rem;
            background-color: #f1f5f9;
            border: none;
            text-align: center;
            width: 100rem;
          }
          .registerLeft {
            width: 100%;
          }
          .getCode {
            width: 32%;
            margin-left: 10px;
          }

          .phoneNum {
            margin-top: 25px;
          }
        }
      }
    }
    ::v-deep(.van-field__control:disabled) {
      color: #343c4b;
      -webkit-text-fill-color: #343c4b;
      text-align: center;
    }
    ::v-deep(.van-field--disabled .van-field__label) {
      color: #343c4b;
    }
    ::v-deep(.van-field__right-icon){
      position: absolute;
      right: 10px;
    }
    ::v-deep(.van-cell) {
      padding: 0 10rem;
      & + .van-cell {
        margin-top: 20rem;
      }

      .van-field__body input {
        height: 44rem;
        padding: 0 20rem;
        border-radius: 24rem;
        background-color: #f1f5f9;
        border: none;
        flex: 1;
      }
    }
    .btnWrap {
      margin: 22rem 26rem;
      .bottomRemark {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
    }
    .hasAccount {
      margin-top: 12rem;
      color: #636c7d;
      font-family: Inter;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      font-size: 14rem;
      span {
        color: #ff2d55;
      }
    }
    .registerWrap {
      margin: 30rem 26rem;
      ::v-deep(.van-checkbox__label) {
        color: #546076;
        font-size: 12rem;
        font-weight: 500;
      }
      .registerBtn {
        margin-top: 20rem;
      }
    }
  }
}
</style>
